package com.uhylab.uhuvinetest;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.uhylab.uhuvinetest.base.UHBase;
import com.uhylab.uhuvinetest.dao.DaoSingleton;
import com.uhylab.uhuvinetest.dao.LocalHistory;
import com.uhylab.uhuvinetest.dao.LocalHistoryDao;
import com.uhylab.uhuvinetest.utils.VolleySingleton;
import com.uhylab.uhuvinetest.utils.sharedpreutils.SharedPreUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * Created by xyb on 16/1/18 at UHylab
 *
 * @version 1.0
 */
public class MyService extends Service {
    private Handler handler;
    private LocalHistoryDao localHistoryDao;
    private VolleySingleton volleySingleton;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return null;

    }


    @Override
    public void onCreate() {
        super.onCreate();
        localHistoryDao = DaoSingleton.getInstance().getLocalHistoryDao();
        volleySingleton = VolleySingleton.getVolleySingleton(getApplicationContext());

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                final QueryBuilder qb = localHistoryDao.queryBuilder();
                qb.where(LocalHistoryDao.Properties.Telephone.eq(SharedPreUtils.getString(MyService.this, "user_tel", "")));
                final List<LocalHistory> localHistories = qb.list();
                String userToken = SharedPreUtils.getString(getApplicationContext(), "user_token", null);
                JSONObject params = new JSONObject();
                if (localHistories != null && localHistories.size() > 0) {
                    if (localHistories.get(0).getAscorbicacid() != null) {
                        try {
                            params.put("telephone", localHistories.get(0).getTelephone());
                            params.put("leukocytes_status", localHistories.get(0).getLeukocytes_status());
                            params.put("leukocytes", localHistories.get(0).getLeukocytes());
                            params.put("nitrite_status", localHistories.get(0).getNitrite_status());
                            params.put("nitrite", localHistories.get(0).getNitrite());
                            params.put("urobilinogen_status", localHistories.get(0).getUrobilinogen_status());
                            params.put("urobilinogen", localHistories.get(0).getUrobilinogen());
                            params.put("protein_status", localHistories.get(0).getProtein_status());
                            params.put("protein", localHistories.get(0).getProtein());
                            params.put("ph_status", localHistories.get(0).getPh_status());
                            params.put("ph", localHistories.get(0).getPh());
                            params.put("blood_status", localHistories.get(0).getBlood_status());
                            params.put("blood", localHistories.get(0).getBlood());
                            params.put("gravity_status", localHistories.get(0).getGravity_status());
                            params.put("gravity", localHistories.get(0).getGravity());
                            params.put("ketones_status", localHistories.get(0).getKetones_status());
                            params.put("ketones", localHistories.get(0).getKetones());
                            params.put("bilirubin_status", localHistories.get(0).getBilirubin_status());
                            params.put("bilirubin", localHistories.get(0).getBilirubin());
                            params.put("glucose_status", localHistories.get(0).getGlucose_status());
                            params.put("glucose", localHistories.get(0).getGlucose());
                            params.put("ascorbicacid_status", localHistories.get(0).getAscorbicacid_status());
                            params.put("ascorbicacid", localHistories.get(0).getAscorbicacid());
                            params.put("date", localHistories.get(0).getDate());
                        }catch (Exception e){

                        }

                    }
                }
                JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, UHBase.newInsertHistory
                        + "token=" + userToken
                        , params, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (localHistories != null && localHistories.size() > 0) {
                            localHistoryDao.deleteAll();
                        }


                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {


                    }
                }) {
//                    @Override
//                    protected Map<String, String> getParams() throws AuthFailureError {
//                        Map<String, String> params = new HashMap<String, String>();
//
//                        return params;
//                    }

                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        headers.put("Accept", "application/json");
                        headers.put("Content-Type", "application/json; charset=UTF-8");
                        return headers;
                    }
                };
                if (localHistories != null && localHistories.size() > 0) {
                    volleySingleton.removeRequest("insertHistory");
                    volleySingleton.addQueue(request, "insertHistory");
                }
                handler.sendEmptyMessageDelayed(1
                        , 10000);
                return false;
            }
        });
        Message message = new Message();
        handler.sendMessage(message);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
